import requests
import json
import codecs
import os
from numpy import mean
import copy
import Levenshtein

IP = "127.0.0.1"
PORT = "8000"
MIN_SIZE = 480
MAX_SIZE = 6000


def post_ocr(image_path):
    try:
        files = {
            "srcImage": open(image_path, "rb")
        }
        r = requests.post(url="http://{}:{}/api/v1.1/certificateOCR".format(IP, PORT), files=files)
    except Exception as e:
        raise Exception(e)
    return r.json()


def write_test_json():
    image_dir = os.path.join(BasePath, "testImage")
    json_dir = os.path.join(BasePath, "testJson")
    for image_name in os.listdir(image_dir):
        result = post_ocr(os.path.join(image_dir, image_name))
        if not result:
            print(f"{image_name}图片不符合要求")
            continue
        if result["code"] != 200:
            print(image_name)
            raise Exception
        with codecs.open(os.path.join(json_dir, image_name.split(".")[0] + ".json"), "w", "utf8") as f:
            f.write(json.dumps(result, indent=2, ensure_ascii=False) + "\n")


def cal_total_acc(base_dict, doc_dict, total_required, total_optional):
    result = copy.deepcopy(base_dict)
    for file_name in base_dict:
        result[file_name]["requiredMean"] = doc_dict[file_name]["required"]
        result[file_name]["optionalMean"] = doc_dict[file_name]["optional"]
    result["requiredTotal"] = round(float(mean(total_required)), 3)
    result["optionalTotal"] = round(float(mean(total_optional)), 3)
    result["total"] = round(float(mean(total_required+total_optional)), 3)
    return result


def calculate_acc():
    pred_json_dir = os.path.join(BasePath, "testJson")
    real_json_dir = os.path.join(BasePath, "realJson")
    acc_dict = {}

    for name in os.listdir(pred_json_dir):
        # print(name)
        # if name in ["医疗器械注册证1.json"]:
        #     continue
        with codecs.open(os.path.join(pred_json_dir, name), "r", "utf8") as f1:
            pred = json.loads(f1.read())["data"]
        with codecs.open(os.path.join(real_json_dir, name), "r", "utf8") as f1:
            content = f1.read().replace("\ufeff", "").replace("\xef\xbb\xbf", "").replace("\n", "")
            real = json.loads(content)["data"]
        if pred["certificateName"] == "营业执照":
            required_fields = ["supplierName", "certificateCode", "legalRepresentative", "certificateValidity"]
            optional_fields = ["businessScope", "issueDate"]
        elif pred["certificateName"] in ["药品生产许可证", "药品经营许可证", "医疗器械生产许可证", "医疗器械经营许可证", "医疗器械生产备案凭证", "医疗器械经营备案凭证"]:
            required_fields = ["supplierName", "certificateCode", "legalRepresentative", "certificateValidity",
                               "businessScope"]
            optional_fields = ["issueDate"]
        elif pred["certificateName"] in ["药品注册批件", "医疗器械备案证", "医疗器械注册证"]:
            required_fields = ["manufacturer", "certificateCode", "certificateValidity"]
            optional_fields = [
                "supplierName", "productName", "productSpecification", "issueDate", "productValidity",
                "registerRepresentative", "productAddress", "dosageForm", "structComposition",
                "registerAddress", "applicationScope", "registerAddress", "legalRepresentative"]
        else:
            print(name)
            print(pred["certificateName"])
            raise Exception(name)

        r_total_sim = dict()
        for filed1 in required_fields:
            sim = Levenshtein.ratio(pred[filed1], real[filed1])
            r_total_sim[filed1] = round(sim, 3)

        o_total_sim = dict()
        for filed2 in optional_fields:
            sim = Levenshtein.ratio(pred[filed2], real[filed2])
            o_total_sim[filed2] = round(sim, 3)

        acc_dict[name] = {
            "required": r_total_sim,
            "optional": o_total_sim
        }

    doc_acc = {}
    total_required = []
    total_optional = []
    for file_name, val in acc_dict.items():
        required = [val for val in val["required"].values()]
        required_mean_acc = mean(required)
        optional = [val for val in val["optional"].values()]
        optional_mean_acc = mean(optional)
        total_required.extend(required)
        total_optional.extend(optional)
        doc_acc[file_name] = {
            "required": round(float(required_mean_acc), 3),
            "optional": round(float(optional_mean_acc), 3)
        }
    result = cal_total_acc(acc_dict, doc_acc, total_required, total_optional)
    data = json.dumps(result, indent=2, ensure_ascii=False)
    print(data)
    with codecs.open("result.json", "w", "utf8") as f:
        f.write(data)


if __name__ == "__main__":
    BasePath = "/home/fish/download/证照示例/testFirst"
    write_test_json()
    calculate_acc()
